package com.huazai.yangge.jmm;

import lombok.Data;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * volatile 不具备原子性
 *
 * @author huazai
 * @date 2024/2/23
 */
public class VolatileNotAtomicDemo {

    public static void main(String[] args) throws InterruptedException {
        AddTest addTest = new AddTest();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    for (int j = 0; j < 1000; j++) {
                        addTest.add();
                    }
                } finally {
                    countDownLatch.countDown();
                }
            }, "t" + i).start();
        }

        countDownLatch.await();
        // 实际值应该是1000
        System.out.println("result " + addTest.getNum());
    }
}

@Data
class AddTest {
    //public volatile int num;
    public int num;

    public void add() {
        num++;
    }

    //public synchronized void add() {
    //     num += 1;
    //}
}
